package leetCode;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author Sven
 * @Desc
 * @date 4/12/22 14:45
 */
public class BinaryTreeInorderTranversal_94 {

    //循环解法
    public List<Integer> inorderTraversal(TreeNode root) {
         List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        //左侧节点全部压入栈
        while (root != null ){
            stack.push( root);
            root = root.left;
        }

        // pop左侧节点 打印 压入右侧节点(同时压入左侧节点)
        while ( !stack.empty()){
            //pop并打印节点
            TreeNode node = stack.pop();
            res.add( node.val);
            node = node.right;
            while (( node != null)){
                stack.push(node);
                node = node.left;

            }
        }
        return res;
    }

    //递归解法
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        recurcive( root,res);
        return res;
    }

    public void recurcive( TreeNode node , List<Integer> res){
        //结束条件
        if( node == null ){
            return;
        }
        //递归调用
        recurcive(node.left, res);
        res.add( node.val);
        recurcive(node.right, res);
    }



    /**
     * Definition for a binary tree node.
*/
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
